package com.ly.lypicturebackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ly.lypicturebackend.api.aliyunai.AliYunAiApi;
import com.ly.lypicturebackend.api.aliyunai.model.CreateOutPaintingTaskRequest;
import com.ly.lypicturebackend.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.ly.lypicturebackend.exception.BusinessException;
import com.ly.lypicturebackend.exception.ErrorCode;
import com.ly.lypicturebackend.exception.ThrowUtil;
import com.ly.lypicturebackend.manager.CosManager;
import com.ly.lypicturebackend.manager.upload.FilePictureUpload;
import com.ly.lypicturebackend.manager.upload.PictureUploadTemplate;
import com.ly.lypicturebackend.manager.upload.UrlPictureUpload;
import com.ly.lypicturebackend.mapper.PictureMapper;
import com.ly.lypicturebackend.model.dto.picture.*;
import com.ly.lypicturebackend.model.entity.Picture;
import com.ly.lypicturebackend.model.entity.Space;
import com.ly.lypicturebackend.model.entity.User;
import com.ly.lypicturebackend.model.enums.PictureReviewStatusEnum;
import com.ly.lypicturebackend.model.vo.PictureVo;
import com.ly.lypicturebackend.model.vo.UserVO;
import com.ly.lypicturebackend.service.PictureService;
import com.ly.lypicturebackend.service.SpaceService;
import com.ly.lypicturebackend.service.UserService;
import com.ly.lypicturebackend.utils.ColorSimilarUtils;
import com.ly.lypicturebackend.utils.ColorTransUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.IOException;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author luyi
 * @description 针对表【picture(图片)】的数据库操作Service实现
 * @createDate 2024-12-31 20:29:12
 */
@Slf4j
@Service
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture> implements PictureService {
    @Resource
    private CosManager cosManager;
    @Resource
    private UserService userService;
    @Resource
    private FilePictureUpload filePictureUpload;
    @Resource
    private UrlPictureUpload urlPictureUpload;
    @Resource
    private SpaceService spaceService;
    @Resource
    private TransactionTemplate transactionTemplate;
    @Resource
    private AliYunAiApi aliYunAiApi;

    @Override
    public PictureVo uploadPicture(Object inputSource, PictureUploadRequest pictureUploadRequest, User loginUser) {
        ThrowUtil.throwIf(inputSource==null, ErrorCode.PARAMS_ERROR);
        ThrowUtil.throwIf(loginUser==null, ErrorCode.NOT_LOGIN_ERROR);
        //判断是新增还是修改
        Long pictureId=null;
        if (pictureUploadRequest != null) {
            pictureId=pictureUploadRequest.getId();
        }
        // 校验空间是否存在
        Long spaceId = pictureUploadRequest.getSpaceId();
        if (spaceId != null) {
            Space space = spaceService.getById(spaceId);
            ThrowUtil.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            /*// 必须空间创建人（管理员）才能上传
            if (!loginUser.getId().equals(space.getUserId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间权限");
            }*/
            if(space.getTotalCount()>space.getMaxCount()){
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间图片数量已达上限");
            }
            if(space.getTotalSize()>space.getMaxSize()){
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间图片大小已达上限");
            }
        }
        // 如果是更新图片，需要校验图片是否存在
        if (pictureId != null) {
            Picture oldPicture = this.getById(pictureId);
            ThrowUtil.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
            /*// 仅本人或管理员可编辑
            if (!oldPicture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }*/
            // 校验空间是否一致
            // 没传 spaceId，则复用原有图片的 spaceId
            if (spaceId == null) {
                if (oldPicture.getSpaceId() != null) {
                    spaceId = oldPicture.getSpaceId();
                }
            } else {
                // 传了 spaceId，必须和原有图片一致
                if (ObjUtil.notEqual(spaceId, oldPicture.getSpaceId())) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间 id 不一致");
                }
            }
        }
        //上传图片的路径
        String uploadPrefix;
        if(spaceId==null){
            uploadPrefix=String.format("public/%s", loginUser.getId());
        }else {
            uploadPrefix=String.format("space/%s",loginUser.getId());
        }
        //根据上传类型判断使用哪种上传方式
        PictureUploadTemplate pictureUploadTemplate=filePictureUpload;
        if(inputSource instanceof String){
            pictureUploadTemplate=urlPictureUpload;
        }
        UploadPictureResult uploadPictureResult = pictureUploadTemplate.uploadPicture(inputSource, uploadPrefix);
        //构造要入库的图片信息
        Picture picture=new Picture();
        if (uploadPictureResult != null) {
            picture.setUrl(uploadPictureResult.getUrl());
            picture.setSpaceId(spaceId);
            picture.setThumbnailUrl(uploadPictureResult.getThumbnailUrl());
            String picName = uploadPictureResult.getPicName();
            if (pictureUploadRequest != null && StrUtil.isNotBlank(pictureUploadRequest.getPicName())) {
                picName = pictureUploadRequest.getPicName();
            }
            picture.setName(picName);
            picture.setPicSize(uploadPictureResult.getPicSize());
            picture.setPicWidth(uploadPictureResult.getPicWidth());
            picture.setPicHeight(uploadPictureResult.getPicHeight());
            picture.setPicScale(uploadPictureResult.getPicScale());
            picture.setPicFormat(uploadPictureResult.getPicFormat());
            picture.setPicColor(ColorTransUtils.convertColor(uploadPictureResult.getPicColor()));
            picture.setUserId(loginUser.getId());
        }
        //补充审核参数
        this.fillReviewParams(picture, loginUser);
        //判断是修改还是新增，如果id为空则为新增
        if(pictureId!=null){
            picture.setId(pictureId);
            picture.setEditTime(new Date());
        }
        // 开启事务
        Long finalSpaceId = spaceId;
        transactionTemplate.execute(status -> {
            boolean result = this.saveOrUpdate(picture);
            ThrowUtil.throwIf(!result, ErrorCode.OPERATION_ERROR, "图片上传失败");
            if (finalSpaceId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, finalSpaceId)
                        .setSql("totalSize = totalSize + " + picture.getPicSize())
                        .setSql("totalCount = totalCount + 1")
                        .update();
                ThrowUtil.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            return picture;
        });
        return PictureVo.objToVo(picture);
    }

    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
            QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
            if (pictureQueryRequest == null) {
                return queryWrapper;
            }
            // 从对象中取值
            Long id = pictureQueryRequest.getId();
            Long spaceId = pictureQueryRequest.getSpaceId();
            String name = pictureQueryRequest.getName();
            String introduction = pictureQueryRequest.getIntroduction();
            String category = pictureQueryRequest.getCategory();
            List<String> tags = pictureQueryRequest.getTags();
            Long picSize = pictureQueryRequest.getPicSize();
            Integer picWidth = pictureQueryRequest.getPicWidth();
            Integer picHeight = pictureQueryRequest.getPicHeight();
            Double picScale = pictureQueryRequest.getPicScale();
            String picFormat = pictureQueryRequest.getPicFormat();
            String searchText = pictureQueryRequest.getSearchText();
            Long userId = pictureQueryRequest.getUserId();
            String sortField = pictureQueryRequest.getSortField();
            String sortOrder = pictureQueryRequest.getSortOrder();
            Date startEditTime = pictureQueryRequest.getStartEditTime();
            Date endEditTime = pictureQueryRequest.getEndEditTime();
        // 从多字段中搜索
            if (StrUtil.isNotBlank(searchText)) {
                // 需要拼接查询条件
                queryWrapper.and(qw -> qw.like("name", searchText)
                        .or()
                        .like("introduction", searchText)
                );
            }
            queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
            queryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "spaceId", spaceId);
            queryWrapper.isNull(pictureQueryRequest.isNullSpaceId(), "spaceId");
            queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
            queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
            queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
            queryWrapper.like(StrUtil.isNotBlank(picFormat), "picFormat", picFormat);
            queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
            queryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth);
            queryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight);
            queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize);
            queryWrapper.eq(ObjUtil.isNotEmpty(picScale), "picScale", picScale);
            queryWrapper.ge(ObjUtil.isNotEmpty(startEditTime), "editTime", startEditTime);
            queryWrapper.lt(ObjUtil.isNotEmpty(endEditTime), "editTime", endEditTime);
            //审核字段的处理
            Integer reviewStatus = pictureQueryRequest.getReviewStatus();
            String reviewMessage = pictureQueryRequest.getReviewMessage();
            Long reviewerId = pictureQueryRequest.getReviewerId();
            queryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
            queryWrapper.like(StrUtil.isNotBlank(reviewMessage), "reviewMessage", reviewMessage);
            queryWrapper.eq(ObjUtil.isNotEmpty(reviewerId), "reviewerId", reviewerId);
            // JSON 数组查询
            if (CollUtil.isNotEmpty(tags)) {
                for (String tag : tags) {
                    queryWrapper.like("tags", "\"" + tag + "\"");
                }
            }
            // 排序
            queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
            return queryWrapper;
        }

    @Override
    public PictureVo getPictureVo(Picture picture, HttpServletRequest request) {
        PictureVo pictureVo=PictureVo.objToVo(picture);
        Long userId = pictureVo.getUserId();
        if(userId!=null&&userId>0){
            User user = userService.getById(userId);
            if(user!=null){
                UserVO userVO = userService.getUserVo(user);
                pictureVo.setUser(userVO);
            }
        }
        return pictureVo;
    }

    @Override
    public Page<PictureVo> getPictureVoPage(Page<Picture> picturePage, HttpServletRequest request) {
        List<Picture> pictureList = picturePage.getRecords();
        Page<PictureVo> pictureVoPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        //判断是否为空
        if(CollUtil.isEmpty(pictureList)){
            return pictureVoPage;
        }
        //对象===》vo对象
        List<PictureVo> pictureVoList = pictureList.stream().map(PictureVo::objToVo).collect(Collectors.toList());
        //关联查询用户信息
        Set<Long> userIdSet = pictureList.stream().map(Picture::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userlistMap = userService.listByIds(userIdSet).stream().collect(Collectors.groupingBy(User::getId));
        //设置信息
        pictureVoList.forEach(pictureVo -> {
            Long userId = pictureVo.getUserId();
            User user=null;
            if(userlistMap.containsKey(userId)){
                user = userlistMap.get(userId).get(0);
            }
            pictureVo.setUser(userService.getUserVo(user));
        });
        pictureVoPage.setRecords(pictureVoList);
        return pictureVoPage;
    }

    @Override
    public void validPicture(Picture picture) {
        ThrowUtil.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        // 修改数据时，id 不能为空，有参数则校验
        ThrowUtil.throwIf(ObjUtil.isNull(id), ErrorCode.PARAMS_ERROR, "id 不能为空");
        if (StrUtil.isNotBlank(url)) {
            ThrowUtil.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "url 过长");
        }
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtil.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, "简介过长");
        }
    }

    @Override
    public void doPictureReview(PictureReviewRequest pictureReviewRequest, User loginUser) {
        // 校验参数
        Long id = pictureReviewRequest.getId();
        Integer reviewStatus = pictureReviewRequest.getReviewStatus();
        PictureReviewStatusEnum reviewStatusEnum = PictureReviewStatusEnum.getEnumByValue(reviewStatus);
        if (id == null || reviewStatusEnum == null || PictureReviewStatusEnum.REVIEWING.equals(reviewStatusEnum)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 判断是否存在
        Picture oldPicture = this.getById(id);
        ThrowUtil.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 已是该状态
        if (oldPicture.getReviewStatus().equals(reviewStatus)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请勿重复审核");
        }
        // 更新审核状态
        Picture updatePicture = new Picture();
        BeanUtils.copyProperties(pictureReviewRequest, updatePicture);
        updatePicture.setReviewerId(loginUser.getId());
        updatePicture.setReviewTime(new Date());
        boolean result = this.updateById(updatePicture);
        ThrowUtil.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }

    @Override
    public void fillReviewParams(Picture picture, User loginUser) {
        if (userService.isAdmin(loginUser)) {
            // 管理员自动过审
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewerId(loginUser.getId());
            picture.setReviewMessage("管理员自动过审");
            picture.setReviewTime(new Date());
        } else {
            // 非管理员，创建或编辑都要改为待审核
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
        }
    }

    @Override
    public Integer uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {
        String searchText = pictureUploadByBatchRequest.getSearchText();
        String namePrefix = pictureUploadByBatchRequest.getNamePrefix();
        if(StrUtil.isBlank(namePrefix)){
            namePrefix=searchText;
        }
        // 格式化数量
        Integer count = pictureUploadByBatchRequest.getCount();
        ThrowUtil.throwIf(count > 30, ErrorCode.PARAMS_ERROR, "最多 30 条");
        // 要抓取的地址
        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1", searchText);
        Document document;
        try {
            document = Jsoup.connect(fetchUrl).get();
        } catch (IOException e) {
            log.error("获取页面失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取页面失败");
        }
        Element div = document.getElementsByClass("dgControl").first();
        if (ObjUtil.isNull(div)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取元素失败");
        }
        Elements imgElementList = div.select("img.mimg");
        int uploadCount = 0;
        for (Element imgElement : imgElementList) {
            String fileUrl = imgElement.attr("src");
            if (StrUtil.isBlank(fileUrl)) {
                log.info("当前链接为空，已跳过: {}", fileUrl);
                continue;
            }
            // 处理图片上传地址，防止出现转义问题
            int questionMarkIndex = fileUrl.indexOf("?");
            if (questionMarkIndex > -1) {
                fileUrl = fileUrl.substring(0, questionMarkIndex);
            }
            // 上传图片
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            if(StrUtil.isNotBlank(namePrefix)){
                pictureUploadRequest.setPicName(namePrefix + (uploadCount+1));
            }
            try {
                PictureVo pictureVO = this.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
                log.info("图片上传成功, id = {}", pictureVO.getId());
                uploadCount++;
            } catch (Exception e) {
                log.error("图片上传失败", e);
                continue;
            }
            if (uploadCount >= count) {
                break;
            }
        }
        return uploadCount;
    }

    @Async
    @Override
    public void clearPictureFile(Picture oldPicture) {
        // 判断该图片是否被多条记录使用
        String pictureUrl = oldPicture.getUrl();
        long count = this.lambdaQuery()
                .eq(Picture::getUrl, pictureUrl)
                .count();
        // 有不止一条记录用到了该图片，不清理
        if (count > 1) {
            return;
        }
        // FIXME 注意，这里的 url 包含了域名，实际上只要传 key 值（存储路径）就够了
        cosManager.deleteObject(oldPicture.getUrl());
        // 清理缩略图
        String thumbnailUrl = oldPicture.getThumbnailUrl();
        if (StrUtil.isNotBlank(thumbnailUrl)) {
            cosManager.deleteObject(thumbnailUrl);
        }
    }

    @Override
    public void checkPictureAuth(User loginUser, Picture picture) {
        Long spaceId = picture.getSpaceId();
        if (spaceId == null) {
            // 公共图库，仅本人或管理员可操作
            if (!picture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        } else {
            // 私有空间，仅空间管理员可操作
            if (!picture.getUserId().equals(loginUser.getId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
    }

    @Override
    public void deletePicture(long pictureId, User loginUser) {
        ThrowUtil.throwIf(pictureId <= 0, ErrorCode.PARAMS_ERROR);
        ThrowUtil.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 判断是否存在
        Picture oldPicture = this.getById(pictureId);
        ThrowUtil.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 校验权限
        //改为注解鉴权
        //checkPictureAuth(loginUser, oldPicture);
        // 开启事务
        transactionTemplate.execute(status -> {
            // 操作数据库
            boolean result = this.removeById(pictureId);
            ThrowUtil.throwIf(!result, ErrorCode.OPERATION_ERROR);
            // 释放额度
            Long spaceId = oldPicture.getSpaceId();
            if (spaceId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, spaceId)
                        .setSql("totalSize = totalSize - " + oldPicture.getPicSize())
                        .setSql("totalCount = totalCount - 1")
                        .update();
                ThrowUtil.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            return true;
        });
        // 异步清理文件
        this.clearPictureFile(oldPicture);
    }

    @Override
    public void editPicture(PictureEditRequest pictureEditRequest, User loginUser) {
        // 在此处将实体类和 DTO 进行转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureEditRequest, picture);
        // 注意将 list 转为 string
        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
        // 设置编辑时间
        picture.setEditTime(new Date());
        // 数据校验
        this.validPicture(picture);
        // 判断是否存在
        long id = pictureEditRequest.getId();
        Picture oldPicture = this.getById(id);
        ThrowUtil.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 校验权限
        //改为注解鉴权
        //checkPictureAuth(loginUser, oldPicture);
        // 补充审核参数
        this.fillReviewParams(picture, loginUser);
        // 操作数据库
        boolean result = this.updateById(picture);
        ThrowUtil.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }

    @Override
    public List<PictureVo> searchPictureByColor(Long spaceId, String picColor, User loginUser) {
        //1、校验参数
        ThrowUtil.throwIf(spaceId==null||StrUtil.isBlank(picColor), ErrorCode.PARAMS_ERROR);
        ThrowUtil.throwIf(loginUser==null, ErrorCode.NO_AUTH_ERROR);
        //2、校验权限
        Space space = spaceService.getById(spaceId);
        ThrowUtil.throwIf(space==null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        if (!loginUser.getId().equals(space.getUserId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间权限");
        }
        //3、查询该空间下的图片，且图片颜色不能为空
        List<Picture> pictureList = this.lambdaQuery()
                .eq(Picture::getSpaceId, spaceId)
                .isNotNull(Picture::getPicColor)
                .list();
        ThrowUtil.throwIf(CollUtil.isNotEmpty(pictureList), ErrorCode.NOT_FOUND_ERROR, "该空间下没有图片");
        //将传入的picColor进行预处理，将颜色值转换为RGB值
        Color targerColor = Color.decode(picColor);
        //4、查询相似图片并排序
        List<PictureVo> pictureVoList=pictureList.stream()
                .sorted(Comparator.comparingDouble(picture -> {
                    // 获取图片颜色并预处理
                    String hexColor = picture.getPicColor();
                    if (StrUtil.isBlank(hexColor)){
                        return Integer.MAX_VALUE;
                    }
                    Color color = Color.decode(hexColor);
                    return -ColorSimilarUtils.calculateSimilarity(targerColor, color);
                }))
                .limit(12)
                .map(PictureVo::objToVo)
                .collect(Collectors.toList());
        return pictureVoList;
    }

    @Override
    public void editPictureByBatch(PictureEditByBatchRequest pictureEditByBatchRequest, User loginUser) {
        //1、校验参数
        List<Long> pictureIdList = pictureEditByBatchRequest.getPictureIdList();
        Long spaceId = pictureEditByBatchRequest.getSpaceId();
        String category = pictureEditByBatchRequest.getCategory();
        List<String> tags = pictureEditByBatchRequest.getTags();
        ThrowUtil.throwIf(CollUtil.isEmpty(pictureIdList), ErrorCode.PARAMS_ERROR);
        ThrowUtil.throwIf(spaceId==null, ErrorCode.PARAMS_ERROR);
        //2、校验空间权限和身份权限
        Space space = spaceService.getById(spaceId);
        ThrowUtil.throwIf(space==null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        if (!loginUser.getId().equals(space.getUserId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间权限");
        }
        //3、查询指定图片，仅选择需要的字段
        List<Picture> pictureList = this.lambdaQuery()
                .select(Picture::getId, Picture::getSpaceId)
                .eq(Picture::getSpaceId, spaceId)
                .in(Picture::getId, pictureIdList)
                .list();
        if(CollUtil.isEmpty(pictureList)){
            return;
        }
        //4、更新分类和标签
        pictureList.forEach(picture -> {
            if(StrUtil.isNotBlank(category)){
                picture.setCategory(category);
            }
            if(CollUtil.isNotEmpty(tags)){
                picture.setTags(JSONUtil.toJsonStr(tags));
            }
        });
        String nameRule = pictureEditByBatchRequest.getNameRule();
        this.fillPictureWithNameRule(pictureList, nameRule);
        //5、操作数据库进行批量更新
        boolean result = this.updateBatchById(pictureList);
        ThrowUtil.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }

    /**
     * nameRule: 图片{序号}
     * @param pictureList 图片列表
     * @param nameRule 图片名称
     */
    private void fillPictureWithNameRule(List<Picture> pictureList, String nameRule) {
        if (StrUtil.isBlank(nameRule)||CollUtil.isEmpty(pictureList)) {
            return;
        }
        long count = 1;
        try {
            for (Picture picture : pictureList) {
                String newName = nameRule.replace("\\{序号}", String.valueOf(count++));
                picture.setName(newName);
            }
        }catch (Exception e){
            log.error("批量更新图片名称失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "批量更新图片名称失败");
        }
    }

    @Override
    public CreateOutPaintingTaskResponse createPictureOutPaintingTask(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest, User loginUser) {
        // 获取图片信息
        Long pictureId = createPictureOutPaintingTaskRequest.getPictureId();
        Picture picture = Optional.ofNullable(this.getById(pictureId))
                .orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_ERROR));
        // 权限校验
        //改为注解鉴权
        //checkPictureAuth(loginUser, picture);
        // 构造请求参数
        CreateOutPaintingTaskRequest taskRequest = new CreateOutPaintingTaskRequest();
        CreateOutPaintingTaskRequest.Input input = new CreateOutPaintingTaskRequest.Input();
        input.setImageUrl(picture.getUrl());
        taskRequest.setInput(input);
        BeanUtil.copyProperties(createPictureOutPaintingTaskRequest, taskRequest);
        // 创建任务
        return aliYunAiApi.createOutPaintingTask(taskRequest);
    }

}




